<?php
/**
 * View-helper для генераци dojo.data объктов
 *
 *
 * Originaly copied from http://github.com/SpiffyJr/SZend/raw/master/Dojo/View/Helper/DataStore.php
 *
 */
class Wlib_Dojo_View_Helper_DataStore extends Zend_Dojo_View_Helper_Dijit
{
    const MODE_GENERATE_STORE_AUTO = 1;
    const MODE_GENERATE_STORE_PROGRAMATIC = 2;
    const MODE_GENERATE_STORE_DECLARATIVE = 3;
    
    /**
     * DataStore view helper.
     *
     * @example
     *  
     *
     *
     * @param string $id JavaScript id for the data store.
     * @param string $dojoType DojoType of the data store (e.g., dojox.data.QueryReadStore)
     * @param array $attribs Attributes for the data store.
     */
    public function dataStore($id = '', $dojoType = '', array $attribs = array(),
                              $generateMode = self::MODE_GENERATE_STORE_AUTO)
    {
        if (!$id || !$dojoType) {
            throw new Zend_Exception('Invalid arguments: required jsId and dojoType.');
        }

        $this->dojo->requireModule($dojoType);

        // Programmatic
        if ($generateMode === self::MODE_GENERATE_STORE_PROGRAMATIC
            || ($generateMode === self::MODE_GENERATE_STORE_AUTO && $this->_useProgrammatic()
                && !$this->_useProgrammaticNoScript()
                )
        ) {
            $this->dojo->addJavascript('var ' . $id . ";\n");
            $js = $id . ' = ' . 'new ' . $dojoType . '(' . Zend_Json::encode($attribs) . ");";
            $this->dojo->_addZendLoad("function(){{$js}}");
            return '';
        }

        if ($generateMode === self::MODE_GENERATE_STORE_DECLARATIVE
            || $generateMode === self::MODE_GENERATE_STORE_AUTO
        ) {
            // Set extra attribs for declarative
            if (!array_key_exists('id', $attribs)) {
                $attribs['id'] = $id;
            }

            if (!array_key_exists('jsId', $attribs)) {
                $attribs['jsId'] = $id;
            }

            if (!array_key_exists('dojoType', $attribs)) {
                $attribs['dojoType'] = $dojoType;
            }

            return '<div' . $this->_htmlAttribs($attribs) . "></div>\n";
        }

        throw new Zend_Exception('Unknown generate mode');
    }
}